package threadLearn.producerconsumer.v3;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class Producer implements Runnable{
	
    private List<Integer> queue;
    private int length;
    private static AtomicInteger count = new AtomicInteger(0);

    public Producer(List<Integer> queue, int length) {
        this.queue = queue;
        this.length = length;
    }

    @Override
    public void run() {
        try {
            while (true) {

                if (Thread.currentThread().isInterrupted())
                    break;
                Random r = new Random();
                int temp = count.incrementAndGet();
                System.out.println(Thread.currentThread().getId() + " 生产了：" + temp);
                Integer data = new Integer(temp);
                
                synchronized (queue) {
                    if (queue.size() >= length) {
                        queue.notifyAll();
                        queue.wait();
                    } else
                        queue.add(data);
                }
                Thread.sleep(r.nextInt(1500));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
